var express = require('express');
var router = express.Router();
var { customQuery } = require('../mysql/index')
// 查询comment表
router.get('/', async function (req, res, next) {
    try {
        const {limit = 10, offset = 0,id} = req.query;
        console.log('进入comment接口',id)
        let whereClause = `WHERE parent_id = ${id}`;
        const countSql = `SELECT COUNT(*) AS total FROM comment ${whereClause}`;
        const selectSql = `SELECT
                          user_list.head_photo,
                          user_list.real_name,
                          comment.*
                          FROM user_list
                          LEFT JOIN comment ON user_list.id = comment.user_id
                          ${whereClause}
                          ORDER BY comment.id DESC LIMIT ${limit} OFFSET ${offset}`;
        // const selectSql = `SELECT * FROM comment WHERE parent_id = ${id}  ORDER BY id DESC LIMIT ${limit} OFFSET ${offset}`;
        const result = await customQuery(countSql);
        const total = result[0].total;
        console.log(111111111111111111,total)
        console.log('resultresultresult',result)
        const res1 = await customQuery(selectSql);
        console.log(res1)
        const results = res1.map(item => {
            item.content = item.content.toString('utf8');
            return item
        });
        console.log(4444444444444,results)
        return res.status(200).send({code: 200, msg: '查询成功', data: {total, list: results}});
    } catch (error) {
        return res.status(200).send({code: 500, msg: '查询失败', error: error});
    }
});

// get请求 all
router.get('/all', async function (req, res, next) {
    try {
        const {limit = 10, page = 1, query} = req.query;
        console.log('进入接口',limit,page,query)
        const offset = (page - 1) * limit;
        let whereClause = '';
        if (query) {
            whereClause = `WHERE (user_name LIKE '%${query}%' OR for_name LIKE '%${query}%')`;
        }
        const countSql = `SELECT COUNT(*) AS total FROM comment ${whereClause}`;
        const selectSql = `SELECT
                          user_list.head_photo,
                          user_list.real_name,
                          comment.*
                          FROM user_list
                          RIGHT JOIN comment ON user_list.id = comment.user_id
                          ${whereClause}
                          ORDER BY comment.id DESC LIMIT ${limit} OFFSET ${offset}`;
        const result = await customQuery(countSql);
        const total = result[0].total;
        console.log('total',total)
        const res1 = await customQuery(selectSql);
        console.log('res1',res1.length)
        const results = res1.map(item => {
            item.content = item.content.toString('utf8');
            return item
        });
        return res.status(200).send({code: 200, msg: '查询成功', data: {total, list: results}});
    } catch (error) {
        return res.status(200).send({code: 500, msg: '查询失败', error: error});
    }
});


// 添加数据到comment表
router.post('/add', function (req, res, next) {
    let { content, user_id, user_name, for_id, for_name, parent_id, type } = req.body;
    console.log(content, user_id, user_name, for_id, for_name, parent_id, type );
    const regex = /^<p>(&nbsp;\s*)*<\/p>$/;
    console.log('regex.test(content)', regex.test(content))
    if (regex.test(content)) {
        content = '';
    }
    if (!content) {
        return res.status(200).send({ code: 400, msg: '请输入内容' });
    }
    console.log('进入add接口', content, user_id, user_name)
    const create_date = new Date().toISOString().slice(0, 19).replace('T', ' ');
    const sql = `INSERT INTO comment (content, create_time, user_id, user_name, for_id, for_name, parent_id, type, \`like\`) VALUES ('${content.replaceAll("'", '"')}', '${create_date}', ${user_id}, '${user_name}', ${for_id}, '${for_name}', ${parent_id}, '${type}', 0)`;
    console.log(sql)
    customQuery(sql)
        .then(results => {
            const newCommentSql = `SELECT
                                  user_list.head_photo,
                                  user_list.real_name,
                                  comment.*
                                  FROM user_list
                                  LEFT JOIN comment ON user_list.id = comment.user_id
                                  WHERE comment.id = ${results.insertId}`;
            customQuery(newCommentSql)
                .then(newComment => {
                    newComment[0].content = newComment[0].content.toString('utf8');
                    return res.status(200).send({ code: 200, msg: '评论成功', list: newComment });
                })
                .catch(error => {
                    console.log(error)
                    return res.status(200).send({ code: 500, msg: '评论时出错', error: error });
                });
            // return res.status(200).send({ code: 200, msg: '评论成功', list: results });
        })
        .catch(error => {
            console.log(error)
            return res.status(200).send({ code: 500, msg: '评论时出错', error: error });
        });
});

// like接口
router.post('/like', function (req, res, next) {
    let {id, type = 1, comment_like_id,user_id} = req.body;
    console.log(1111111111111,id, type, comment_like_id)
    const sql = `UPDATE comment SET \`like\` = \`like\` ${type === 1 ? '+' : '-'} 1 WHERE id = ${id}`;
    customQuery(sql)
        .then(results => {
            if (comment_like_id) {
                const sql2 = `UPDATE user_list SET comment_like_id = '${comment_like_id}' WHERE id = ${user_id}`;
                customQuery(sql2)
                    .then(results => {
                        return res.status(200).send({code: 200, msg: '操作成功', list: results});
                    })
                    .catch(error => {
                        return res.status(200).send({code: 500, msg: '操作失败', error: error});
                    });
            } else {
                return res.status(200).send({code: 200, msg: '操作成功', list: results});
            }
        })
        .catch(error => {
            return res.status(200).send({code: 500, msg: '操作失败', error: error});
        });
});

// delete接口
router.post('/delete', function (req, res, next) {
    let {id} = req.body;
    const sql = `DELETE FROM comment WHERE id = ${id}`;
    customQuery(sql)
        .then(results => {
            return res.status(200).send({code: 200, msg: '删除成功', list: results});
        })
        .catch(error => {
            return res.status(200).send({code: 500, msg: '删除时出错', error: error});
        });
});

module.exports = router;



